/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Admin;

import CRUD.RuleFacadeLocal;
import Entity.Rule;
import Entity.RulePK;
import java.math.BigInteger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author WinKiQue58
 */
@Stateless
public class Business_Rules implements Business_RulesLocal {
   
    @PersistenceContext(unitName = "S3R4_Orcl-ejbPU")
        private EntityManager em;
     
    @EJB  private RuleFacadeLocal ruleFacade;
    
     public boolean CreateRule(String name, Double value, BigInteger idEnterprise,
             BigInteger idBranch) 
     {
        Rule r=null;
        Query q1= em.createQuery("SELECT r FROM Rule r WHERE r.name = :NAME WHERE "
                  + "oi.orderItemPK.idBranchenterprise = :A AND "
                  + "oi.orderItemPK.idEnterprise = :B"); 
        q1.setParameter("A", idBranch);
        q1.setParameter("B", idEnterprise);
        
        //--If is not created, we need to do it
        try{
         r= (Rule) q1.getSingleResult();
         } catch(NoResultException e) {
             
        Query q2= em.createQuery("SELECT MAX(r.rulePK.idRule) FROM Rule r WHERE "
                  + "oi.orderItemPK.idBranchenterprise = :A AND "
                  + "oi.orderItemPK.idEnterprise = :B"); 
        q2.setParameter("A", idBranch);
        q2.setParameter("B", idEnterprise);
        
        BigInteger newID=(BigInteger)q2.getSingleResult();
        
         RulePK rulePK=new RulePK( newID.add(new BigInteger("1")) , idBranch, idEnterprise);
         Rule rule=new Rule(rulePK, name, value);
         ruleFacade.create(rule);
         return true;
        }
         
        //--If exist, then is neccesary to update value
         r.setS3r4Value(value);
         ruleFacade.edit(r);
         return true;
     }
     
     
    
}
